package com.lhg.framework.core;

import com.lhg.framework.emq.EmqClient;
import com.lhg.pojo.entity.GPS;
import com.lhg.service.GpsService;
import com.lhg.service.QuotaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author 刘华桂
 */
@Component
@Slf4j
public class Monitor {

    @Autowired
    private EmqClient emqClient;

    @Autowired
    private QuotaService quotaService;

    @Autowired
    private GpsService gpsService;

    @PostConstruct
    public void init(){
        System.out.println("初始化方法，订阅主题");
        emqClient.connect();
        quotaService.getAllSubject().forEach(s -> {
            try {
                // 使用共享订阅的方式进行发布
                emqClient.subscribe("$queue/"+s);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        });

        //订阅gps主题数据
        GPS gps = gpsService.getGps();
        if(gps == null) {
            return;
        }
        try {
            //如果主题不为空
            if(Strings.isNotEmpty(gps.getSubject())){
                emqClient.subscribe("$queue/"+gps.getSubject());
            }
        } catch (MqttException e) {
            log.error("订阅主题出错：",e);
        }
    }
}
